# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
Lemon客户端多线程
"""
import json
import os
import os.path
import requests
from PyQt5 import QtCore
from requests.exceptions import ConnectionError
from urllib3.exceptions import NewConnectionError
from util import server_ip, server_port, post_json, client_version, get_desktop


class ClientUpdate(QtCore.QThread):
    msg = QtCore.pyqtSignal(str)

    def __init__(self):
        super(ClientUpdate, self).__init__()

    def update(self):
        """"""
        check_version_url = f"http://{server_ip}:{server_port}/checkUpdate"
        check_version_data = {"client_version": client_version}
        try:
            check_version_res = requests.post(
                check_version_url, json.dumps(check_version_data)
            )
            if check_version_res.status_code == 200:
                check_version_result = check_version_res.json()
                if check_version_result == 1:
                    self.msg.emit(
                        "<font color=blue>有新版Lemon正在为您下载到桌面...</font>"
                    )
                    download_url = (
                        f"http://{server_ip}:{server_port}/download/Lemon.exe"
                    )
                    try:
                        download_res = requests.get(download_url)
                        if download_res.status_code == 200:
                            download_file = download_res.content
                            desktop = get_desktop()
                            exe_path = rf"{desktop}\Lemon_install.exe"
                            with open(exe_path, "wb") as file:
                                file.write(download_file)
                            os.startfile(exe_path)
                            self.msg.emit(
                                "<font color=blue>新版本已经下载到桌面，请关闭当前程序后安装新版本！</font>"
                            )
                    except (
                        ConnectionRefusedError,
                        NewConnectionError,
                        ConnectionError,
                    ):
                        self.msg.emit(
                            "<font color=red>下载安装包失败，请联系支持人员！</font>"
                        )
                elif check_version_result == 0:
                    ...
        except (ConnectionRefusedError, NewConnectionError, ConnectionError):
            self.msg.emit("<font color=red>检查更新失败，请联系支持人员！</font>")

    def run(self) -> None:
        self.update()


class QueryAccount(QtCore.QThread):
    msg = QtCore.pyqtSignal(str)

    def query_account_info(self):
        url = f"http://{server_ip}:{server_port}/queryAccount"
        res = requests.get(url).json()
        code = res.get("code")
        if code == 1:
            error_desc = res.get("msg")
            self.msg.emit(error_desc)
            return None
        else:
            account_info = res.get("data")
            return account_info


class QueryClientInteraction(QtCore.QThread):
    def __init__(self, data_type):
        super().__init__()
        self.data_type = data_type

    def query_client_interaction(self):
        url = f"http://{server_ip}:{server_port}/queryClientInteraction"
        res = requests.post(url, params={"data_type": self.data_type}).json()
        return res

    def run(self) -> None:
        self.query_client_interaction()


# class QueryBusiness(QtCore.QThread):
#     """查询公司下业务信息"""
#     msg = QtCore.pyqtSignal(str)
#
#     def __init__(self, company_id):
#         super().__init__()
#         self.company_id = company_id
#
#     def query_business_info(self):
#         url = f"http://{server_ip}:{server_port}/queryBusiness"
#         res = requests.get(url, params={'company_id': self.company_id}).json()
#         code = res.get('code')
#         if code == 1:
#             error_desc = res.get('msg')
#             self.msg.emit(error_desc)
#             return None
#         else:
#             business_info = res.get('data')
#             return business_info
#
#     def run(self) -> None:
#         self.query_business_info()


class QueryDataType(QtCore.QThread):
    @staticmethod
    def query_data_type():
        url = f"http://{server_ip}:{server_port}/queryDataType"
        data_type = requests.get(url).json()
        return data_type


class ExportExcel(QtCore.QThread):
    """根据Lemon客户端传输过来的数据，判断要导出什么数据"""

    msg = QtCore.pyqtSignal(str)

    def __init__(self, client_data):
        super().__init__()
        self.client_data = client_data

    def export(self):
        headers = {"Content-Type": "application/json"}
        url = f"http://{server_ip}:{server_port}/exportData"
        res = post_json(url, self.client_data, headers=headers, timeout=120)
        msg = res.get("msg")
        self.msg.emit(str(msg))

    def run(self) -> None:
        self.export()


class ClassicQuote(QtCore.QThread):
    title = QtCore.pyqtSignal(str)

    def __init__(self):
        super().__init__()

    @staticmethod
    def get_hitokoto():
        try:
            res = requests.get("https://v1.hitokoto.cn")
            if res.status_code == 200:
                res_data = res.json()
                hitokoto = res_data.get("hitokoto")
                from_where = res_data.get("from")
                from_who = res_data.get("from_who")
                if from_who is None:
                    from_who = "佚名"
                return (
                    f"<font color=purple>{hitokoto} 丨</font> "
                    f"<font color=vermeil>《{from_where}》</font> "
                    f"<font color=purple> - {from_who}</font>"
                )
        except ConnectionError:
            return None
